package com.dingding.manager.modules.system.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.util.MD5Util;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.system.service.UserService;
import com.google.code.kaptcha.Constants;

@Controller
@RequestMapping(value="sys/v1")
public class LoginController {
	
	
	@Resource(name="userService")
	UserService userService;
	
	/**
	 * @Description: 用户登录       
	 * @date 2016年12月1日 下午3:24:47
	 * @author SUNZHICHENG 
	 * @throws IOException 
	 * @since V2.6.2
	 */
	@RequestMapping(value="/login")
	public String sysLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		String code = request.getParameter("code");
		
		if (ToolUtil.isEmpty(userName) && ToolUtil.isEmpty(passWord)) {
			request.setAttribute("error", "账号或密码不能为空");
			return "login";
		}
		
		if (ToolUtil.isEmpty(code)) {
			request.setAttribute("error", "验证码不能为空");
			return "login";
		}
		
		// 从httpession中获取生成的图片验证码
		HttpSession session = request.getSession();
		String kaptchaCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
				
		if (ToolUtil.isEmpty(kaptchaCode)) {
			request.setAttribute("error", "服务器异常");
			return "login";
		}
		
		if (!kaptchaCode.equals(code)) {
			request.setAttribute("error", "验证码错误");
			return "login";
		}
		
		// 获取主体对象
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, MD5Util.encrypt(passWord));
		subject.login(token);
		ShiroKit.setSessionAttr("user", ShiroKit.getUser());
		return "index";
	}
	
	
	
	
	
	/**
	 * 
	 * @Description: 用户退出       
	 * @date 2016年12月1日 下午3:30:28
	 * @author SUNZHICHENG 
	 * @since V2.6.2
	 */
	@RequestMapping(value="/logout")
	public String sysLogout(HttpServletRequest request, HttpServletResponse response){
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			//调用shiro的logout退出系统
				subject.logout();
				ShiroKit.removeSessionAttr("user");
				return "login";
		}
		return "login";
	}
	
	/**
	 * @Description: 验证当前用户是否属于超级管理员
	 * @date 2017年1月4日 下午4:01:48
	 * @author SUNZHICHENG 
	 * @since V2.6.3
	 */
	@RequestMapping(value="/isAdmin")
	@ResponseBody
	public boolean isAdmin(){
		return ShiroKit.isManager();
	}
	
	
}
